// 2024 02 23 22:06
const WebSocket = require('ws');

const config = require('./config/config')
const wsc = require('./config/ws.config')

const { readFile, writeFile } = require('./lib/lib')
const { findAvailablePort } = require('./lib/AvailablePort')
const { server_start } = require('./lib/express')

// 获取命令行参数
const args = process.argv

findAvailablePort(wsc.config.cmd.port, port => {
    console.log(`websocket端口：\x1B[36m${port}\x1B[0m 可用`)
    wsc.config.cmd.port = port

    writeFile(config.configJson, JSON.stringify({
        wsc: wsc.config
    }))
        .then(() => {

            console.log('配置文件更新成功', `\x1B[32m${config.configJson}\x1B[0m`)
            server_start()
        })

    const wss = new WebSocket.Server({
        port: port
    })

    wsr(wss)
})

function wsr(wss) {

    wss.on('connection', ws => {
        console.log(`\x1B[42m${wss.options.port}\x1B[0m 新的WebSocket连接`)

        function send(data) {
            ws.send(JSON.stringify({
                msg: data,
                code: 0
            }))
        }

        function error(data, code = 1) {
            ws.send(JSON.stringify({
                msg: data,
                code: code
            }))
        }

        // 监听消息事件
        ws.on('message', message => {
            const msg = JSON.parse(message.toString())

            switch (msg.type) {
                case 'connect':
                    readFile(args[2])
                        .then(res => {
                            send({
                                data: res
                            })
                        })
                    break
                default:
                    break;
            }
        })

        // 监听关闭事件
        ws.on('close', () => {
            console.log(`\x1B[46m${wss.options.port}\x1B[0m WebSocket连接关闭`)

            // 终止脚本
            // 如果页面刷新也会触发
            // process.exit(0)
        })
    })
}
